package demo.letcode.top100;

import java.util.HashMap;
import java.util.Map;

public class _LRU {
    private final Map<String, Node> cache = new HashMap<>();
    private final int capacity;
    private int size;
    private Node head;
    private Node tail;

    public _LRU(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    public int get(String key) {
        Node node = cache.get(key);
        if (node == null) {
            return -1;
        }
        moveHead(node);
        return node.val;
    }

    public void put(String key, Integer val) {
        Node node = cache.get(key);
        if (node == null) {
            Node n = new Node(key, val);
            cache.put(key, n);
            addHead(n);
            ++size;
            if (size > capacity) {
                Node tail = removeTail();
                cache.remove(tail.key);
                --size;
            }
        } else {
            node.val = val;
            moveHead(node);
        }
    }

    private void moveHead(Node node) {
        removeNode(node);
        addHead(node);
    }

    private Node removeTail() {
        Node res = tail.pre;
        removeNode(res);
        return res;
    }

    private void addHead(Node node) {
        node.pre = head;
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
    }

    private void removeNode(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    public static void main(String[] args) {

    }

    class Node {
        private String key;
        private Integer val;
        private Node pre;
        private Node next;

        public Node() {
        }

        public Node(String key, Integer val) {
            this.key = key;
            this.val = val;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Integer getVal() {
            return val;
        }

        public void setVal(Integer val) {
            this.val = val;
        }

        public Node getPre() {
            return pre;
        }

        public void setPre(Node pre) {
            this.pre = pre;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

}
